using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

using JsonSharp;
using JsonSharp.Collections;
using JsonSharp.Values;

using System.Globalization;
using Barbar.MapReport.Common;
using Barbar.MapReport.HtmlRender.Operations.Legends;

namespace Barbar.MapReport.HtmlRender.Operations.ValueIndicators {
  internal class ValueIndicatorAgregator {
    private List<FlatPoint> m_Items = new List<FlatPoint>();
    private const decimal MultipleValuesRadiusMultiplier = 1.4m;
    private PointD m_PointD;
    private decimal[] m_Values;
    private Color[] m_Colors;
    private int m_BaseRadius;
    private MercatorProjection m_Projection;
    private string m_HandlerUrl;

    public ValueIndicatorAgregator(int valuesCount, int radius, MercatorProjection projection, string handlerUrl) {
      m_Values = new decimal[valuesCount];
      m_Colors = new Color[valuesCount];
      m_BaseRadius = radius;
      m_Projection = projection;
      m_HandlerUrl = handlerUrl;
    }

    public int BaseRadius {
      get { return m_BaseRadius; }
    }

    public IList<FlatPoint> Items {
      get { return m_Items; }
    }
    
    public int RealRadius {
      get { return (m_Items.Count < 2) ? m_BaseRadius : (int)(m_BaseRadius * MultipleValuesRadiusMultiplier); }
    }

    public void Recalculate() {
      if (m_Items.Count > 0) {
        PointD basePoint = new PointD();
        for (int i = 0; i < m_Values.Length; i++)
          m_Values[i] = 0m;
        foreach (FlatPoint valueIndicator in m_Items) {
          basePoint = basePoint.Add(valueIndicator.ProjectedPoint);
          for (int i = 0; i < m_Values.Length; i++)
            m_Values[i] += valueIndicator[i];
        }
        m_PointD = basePoint.Divide(m_Items.Count);
        for (int i = 0; i < m_Values.Length; i++) {
          m_Values[i] /= m_Items.Count;
        }
      }
    }

    public void SetColor(LegendRangeList legend, int valueIndex) {
      decimal value = m_Values[valueIndex];
      foreach (LegendRange entry in legend) {
        if (entry.From <= value && entry.To >= value) {
          m_Colors[valueIndex] = entry.Color;
          return;
        }
      }
      throw new NotImplementedException();
    }

    public void Add(FlatPoint valueIndicator) {
      m_Items.Add(valueIndicator);
    }

    public GeoPoint GeoPoint {
      get { return m_Projection.ToGeoPoint(m_PointD); }
    }
  }
}
